package ink.metoo.auto.fishpi.call

import com.google.gson.Gson
import ink.metoo.auto.fishpi.ClientCaches
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.chatroom.Message
import ink.metoo.auto.fishpi.chatroom.RedPacket
import okhttp3.WebSocketListener
import kotlin.random.Random

object ChatRoomCall {

    class ChatRoomNode {
        var node: String? = null
        var name: String? = null
        var online: Int? = null
        var weight: Int? = null
    }

    class ChatRoomNodeResult : AbstractBaseResult() {
        var data: String? = null
        var avaliable: Array<ChatRoomNode>? = null
        var apiKey: String? = null
    }

    fun getChatRoomNode() = Requests.sendGetRequest<ChatRoomNodeResult>(
        path = "/chat-room/node/get",
        queryParams = arrayOf(Pair("apiKey", ClientCaches.apiKey))
    )

    fun watchChatRoom(listener: WebSocketListener) = Requests.watchWebSocket(
        url = getChatRoomNode().data ?: throw RuntimeException("get webSocketUrl fail"),
        listener = listener
    )

    class SendMessageBody : AbstractBaseBody() {
        var client: String? = null
        var content: String? = null
    }

    /**
     * @param content 消息内容
     * @param preventDuplication 是否防止重复发送，默认为true，如果为true，则会在消息内容后添加一个随机数，防止重复发送
     */
    fun sendMessage(content: String, preventDuplication: Boolean = true) = Requests.sendJsonRequest<BaseResult>(
        path = "/chat-room/send",
        body = SendMessageBody().fillFormCache {
            it.client = Settings.chatRoom.clientId
            if (preventDuplication) {
                it.content = "$content\n<!-- ${Random.nextLong()} -->"
            } else {
                it.content = content
            }
        }
    )


    data class RedPacketBody(
        var msg: String? = null,
        var money: Int = 32,
        var count: Int = 1,
        var recivers: List<String> = emptyList(),
        /**
         * 红包类型，random(拼手气红包), average(平分红包)，specify(专属红包)，heartbeat(心跳红包)，rockPaperScissors(猜拳红包)
         */
        var type: String,
        var gesture: String? = null
    )

    private val gson = Gson()

    fun sendRedPacket(block: (RedPacketBody) -> Unit): BaseResult {
        val body = RedPacketBody(type = "random")
        block(body)
        val json = gson.toJson(body)
        return sendMessage(content = "[redpacket]${json}[/redpacket]", preventDuplication = false)
    }

    fun modifyTopic(discuss: String): BaseResult {
        return sendMessage(content = "[setdiscuss]${discuss}[/setdiscuss]", preventDuplication = false)
    }

    class OpenRedPacketBody : AbstractBaseBody() {
        var oId: String = ""
        var gesture: String? = null
    }

    class OpenRedPacket : AbstractBaseResult() {
        class Info {
            var count: Int? = null
            var gesture: Int? = null
            var got: Int? = null
            var msg: String? = null
            var userName: String? = null
            // ...
        }

        var info: Info? = null
        var recivers: List<String> = emptyList()
        var who: List<RedPacket.ReceivedInfo> = emptyList()
    }

    fun openRedPacket(oId: String, gesture: String? = null) = Requests.sendJsonRequest<OpenRedPacket>(
        path = "/chat-room/red-packet/open",
        body = OpenRedPacketBody().fillFormCache {
            it.oId = oId
            it.gesture = gesture
        }
    )

    fun getMessageRaw(oId: String) = Requests.sendGetRequest<String>(
        path = "/cr/raw/${oId}",
        queryParams = arrayOf(Pair("apiKey", ClientCaches.apiKey))
    )


    class MoreMessageHistoryResult : AbstractBaseResult() {
        var data: List<Message> = emptyList()
    }

    /**
     * 根据消息id获得历史消息
     *
     * @param oId 消息id
     * @param mode 0: 显示本条及之前之后消息
     * @param mode 1: 显示本条及之前消息
     * @param mode 2: 显示本条及之后消息
     * @param size 显示条数
     * @param type md: markdown
     * @param type html: html
     */
    fun getContextMessage(
        oId: String,
        mode: Int = 0,
        size: Int = 1,
        type: String = "html"
    ) = Requests.sendGetRequest<MoreMessageHistoryResult>(
        path = "/chat-room/getMessage",
        queryParams = arrayOf(
            "apiKey" to ClientCaches.apiKey,
            "oId" to oId,
            "mode" to mode.toString(),
            "size" to size.toString(),
            "type" to type
        )
    )

    fun getGoodMessageRaw(oId: String) = getContextMessage(oId = oId, mode = 1, size = 1, type = "md").data.findLast { it.oId == oId }

    /**
     * 获得历史消息
     *
     * @param page 页码
     * @param type md: markdown, html: html
     */
    fun getMoreMessage(page: Int, type: String = "html") = Requests.sendGetRequest<MoreMessageHistoryResult>(
        path = "/chat-room/more",
        queryParams = arrayOf(
            "apiKey" to ClientCaches.apiKey,
            "page" to page.toString(),
            "type" to type
        )
    )

    fun revokeMessage(oId: String) = Requests.sendJsonRequest<BaseResult>(
        path = "/chat-room/revoke/${oId}",
        method = "DELETE",
        body = CacheBaseBody(),
    )

}